/**
 *@描述：创建知识-知识结构页面，此页面仅为三种结构类型中的代码结构类型。
 * 本系统中，预先设置了三种类型的知识结构类型：文档、代码、流程图，根据不同的类型显示不同的操作页面
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */

import {useEffect, useState} from "react";
import {useUpdateEffect} from "ahooks";
import {Button, message, Typography} from "antd";
import styles from "@/pages/Dashboard/Knowledge/components/Content/style.less";
import ProForm, {ProFormItem} from "@ant-design/pro-form";
import {SaveOutlined} from "@ant-design/icons";
import {ChapterSaveRequest, knowledgeChapterToIdRequest} from "@/pages/Dashboard/Knowledge/service";
import CustomDiagramEditor from "@/pages/Dashboard/Knowledge/components/CustomDiagramEditor";
const { Text } = Typography;


const Diagram = (
    {
        title,
        knowledgeId,
        curSection,
        setKnowledgeId,
        setCurSection,
        structure,
        setStructure,
    }:{
        title:string;
        knowledgeId?:string;
        curSection:AircasKB.Knowledge.SectionItem;
        setKnowledgeId?: (val: string) => void;
        setCurSection?: (val: AircasKB.Knowledge.SectionItem) => void;
        structure:AircasKB.Knowledge.SectionItem[];
        setStructure?: (val: AircasKB.Knowledge.SectionItem[]) => void;
    }
) => {
    const [ loading,setLoading ] = useState(false);
    const [ value,setValue ] = useState("");

    //页面初始化函数
    //todo： useEffect函数
    useEffect(()=>{
        if(!knowledgeId){
            message.warn("请首先进入基本信息页面，填写基本信息！");
            setCurSection?.({
                id: 'basic',
                title: '基本信息'
            })
        }
        if(!curSection.id){
            setValue("");
        }
        else{
            getKnowledgeChapterToId(curSection.id);
        }
    },[curSection.id])

    //todo：useUpdateEffect函数
    useUpdateEffect(() => {
        setCurSection?.(curSection);
    }, [curSection]);

    //根据章节ID获取当前章节的内容，仅在编辑状态使用,调用knowledgeChapterToIdRequest结构
    //TODO:根据章节ID获取当前章节的内容
    const getKnowledgeChapterToId = async (id:string) => {
        const res:AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeChapterToIdResponse> = await knowledgeChapterToIdRequest({
            id:id
        });
        if(res.code == 200){
            // @ts-ignore
            setValue(res.data.content);
        }
    }

    //将当前的章节与现有的章节列表进行合并，并显示
    //TODO:合并章节列表
    const UnionSectionItem = (arr:AircasKB.Knowledge.SectionItem[],obj:AircasKB.Knowledge.SectionItem) => {
        for(let i=0;i<arr.length;i++){
            if(arr[i].title == obj.title){
                arr.splice(i,1,obj);
                break;
            }
        }
        setStructure?.(arr);
    }

    //保存触发函数
    //TODO:保存触发函数
    const doSave = (formData: any) => {
        setLoading(true);
        //设置保存所需要的请求参数
        const requestParams:AircasKB.Knowledge.ChapteSaveRequestParams = {
            id:curSection.id,
            knowledgeId:knowledgeId,
            context:value,
            title:curSection.title,
            type:curSection.type,
            chapterNo:curSection.chapterNo
        }
        // console.log(requestParams);
        //调用ChapterSaveRequest接口保存文档信息
        ChapterSaveRequest(requestParams).then(res => {
            if(res.code == 200){
                setLoading(false);
                message.success("保存成功！");
                const obj:AircasKB.Knowledge.SectionItem = {
                    id:res.data.id,
                    title:res.data.title,
                    type:res.data.type,
                    chapterNo:curSection.chapterNo
                }
                UnionSectionItem(structure,obj);
                setKnowledgeId?.(res.data.knowledgeId);
            }
            else{
                setLoading(false);
                message.error("保存失败！");
            }
        });
    };


    return(
        <div className={styles.wrapper}>
            <div className={styles.subTitle}>
                <Text>{curSection.title}</Text>
            </div>
            <ProForm
                layout="vertical"
                className={styles.form}
                // labelCol={{
                //     style: {
                //         width: 80,
                //     },
                // }}
                initialValues={{}}
                submitter={false}
            >
                <ProFormItem name="content" required noStyle style={{ marginBottom: 20 }}>
                    <CustomDiagramEditor value={value} onChange={setValue} curSection={curSection}/>
                    <br />
                </ProFormItem>
                <ProFormItem>
                    <Button size="large" type="primary" htmlType="submit" icon={<SaveOutlined />} loading={loading} onClick={doSave}>
                        保存
                    </Button>
                </ProFormItem>
            </ProForm>
        </div>
    )
}

export default Diagram;
